package org.dromara.business.utils;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.ThreadLocalRandom;

public class PasswordGenerator {

    private static final String LOWERCASE = "abcdefghijklmnopqrstuvwxyz";
    private static final String UPPERCASE = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    private static final String DIGITS = "0123456789";
    private static final String SPECIAL = "!@#$%^&*()-_=+[]{}|;:,.<>?";

    private static final ThreadLocalRandom THREAD_LOCAL_RANDOM = ThreadLocalRandom.current();

    public static String generate(int length, boolean useUpper, boolean useDigits, boolean useSpecial) {
        if (length < 8) {
            throw new IllegalArgumentException("密码长度至少8位");
        }

        StringBuilder password = new StringBuilder(length);
        List<String> charCategories = new ArrayList<>(4);

        charCategories.add(LOWERCASE);
        if (useUpper) charCategories.add(UPPERCASE);
        if (useDigits) charCategories.add(DIGITS);
        if (useSpecial) charCategories.add(SPECIAL);

        // 确保每个选中的字符类别至少有一个字符
        for (String category : charCategories) {
            password.append(category.charAt(THREAD_LOCAL_RANDOM.nextInt(category.length())));
        }

        // 填充剩余长度
        for (int i = password.length(); i < length; i++) {
            String category = charCategories.get(THREAD_LOCAL_RANDOM.nextInt(charCategories.size()));
            password.append(category.charAt(THREAD_LOCAL_RANDOM.nextInt(category.length())));
        }

        // 打乱顺序
        List<Character> chars = new ArrayList<>();
        for (char c : password.toString().toCharArray()) {
            chars.add(c);
        }
        Collections.shuffle(chars, THREAD_LOCAL_RANDOM);

        StringBuilder result = new StringBuilder();
        for (char c : chars) {
            result.append(c);
        }

        return result.toString();
    }

    public static String generateRobotPassword() {
        return generate(12, true, true, true);
    }

    public static void main(String[] args) {
        System.out.println(generate(10, true, true, true));
    }
}
